package com.matchmealpha;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;

public class ConnectToActivity extends Activity implements OnClickListener {

	private Button leftButton;
	private Button rightButton;
	private Button fbConnectButton;
	private Button fbDisconnectButton;
	private Button twConnectButton;
	private Button twDisconnectButton;

	protected EditText fbPasswordText;
	protected EditText twPasswordText;
	protected EditText fbUsernameText;
	protected EditText twUsernameText;

	private Context context;
	private Handler mHandler = new Handler();

	private static final String[] PERMISSIONS = new String[] {
			"publish_stream", "read_stream", "offline_access" };

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initLayout();
		initListener();
		this.context = this.getParent();
	}

	private void initLayout() {
		setContentView(R.layout.connectto_view);
		leftButton = (Button) this.findViewById(R.id.ConnecttoLeftButton);
		rightButton = (Button) this.findViewById(R.id.ConnecttoRightButton);
		fbUsernameText = (EditText) this
				.findViewById(R.id.ConnecttoFacebookUsername);
		fbPasswordText = (EditText) this
				.findViewById(R.id.ConnecttoFacebookPassword);
		fbConnectButton = (Button) this
				.findViewById(R.id.ConnecttoFacebookConnectButton);
		fbDisconnectButton = (Button) this
				.findViewById(R.id.ConnecttoFacebookDisconnectButton);
		twUsernameText = (EditText) this
				.findViewById(R.id.ConnecttoTwitterUsername);
		twPasswordText = (EditText) this
				.findViewById(R.id.ConnecttoTwitterPassword);
		twConnectButton = (Button) this
				.findViewById(R.id.ConnecttoTwitterConnectButton);
		twDisconnectButton = (Button) this
				.findViewById(R.id.ConnecttoTwitterDisconnectButton);

		rightButton.setVisibility(View.INVISIBLE);
		if (MatchMeTabWidget.mFacebook.isSessionValid()) {
			connectedToFacebook();
		} else {
			disconnectedFromFacebook();
		}
	}

	private void connectedToFacebook() {
		fbDisconnectButton.setEnabled(true);
		fbConnectButton.setEnabled(false);
	}

	private void disconnectedFromFacebook() {
		fbDisconnectButton.setEnabled(false);
		fbConnectButton.setEnabled(true);
	}

	private void initListener() {
		leftButton.setOnClickListener(this);
		fbConnectButton.setOnClickListener(this);
		fbDisconnectButton.setOnClickListener(this);
		twConnectButton.setOnClickListener(this);
		twDisconnectButton.setOnClickListener(this);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("FB Sample App", "onActivityResult(): " + requestCode);
		MatchMeTabWidget.mFacebook.authorizeCallback(requestCode, resultCode,
				data);
	}

	private final class LoginDialogListener implements
			com.facebook.android.Facebook.DialogListener {

		public void onComplete(Bundle values) {
			// Process onComplete
			Log.d("FB Sample App------------",
					"LoginDialogListener.onComplete()");
			connectedToFacebook();
		}

		public void onFacebookError(FacebookError error) {
			// Process error
			Log.d("FB Sample App------------",
					"LoginDialogListener.onFacebookError()");
		}

		public void onError(DialogError error) {
			// Process error message
			Log.d("FB Sample App------------", "LoginDialogListener.onError()");
		}

		public void onCancel() {
			// Process cancel message
			Log
					.d("FB Sample App------------",
							"LoginDialogListener.onCancel()");
		}
	}

	private class LogoutRequestListener implements RequestListener {

		@Override
		public void onComplete(String response, Object state) {
			Log.d("FB Sample App------------",
					"LogoutDialogListener.onComplete()");
			// Only the original owner thread can touch its views
			ConnectToActivity.this.runOnUiThread(new Runnable() {
				public void run() {
					disconnectedFromFacebook();
				}
			});

			// Dispatch on its own thread
			mHandler.post(new Runnable() {
				public void run() {
					Toast.makeText(context, "DISCONNECTED FROM FACEBOOK",
							Toast.LENGTH_LONG);
				}
			});
		}

		@Override
		public void onFacebookError(FacebookError e, Object state) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onFileNotFoundException(FileNotFoundException e,
				Object state) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onIOException(IOException e, Object state) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onMalformedURLException(MalformedURLException e,
				Object state) {
			// TODO Auto-generated method stub
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case (R.id.ConnecttoLeftButton):
			TimelineGroup.timelineGroup.back();
			break;

		case (R.id.ConnecttoFacebookConnectButton):
			// Intent intent3 = new Intent(this, MatchMeFacebookActivity.class);
			// intent3.putExtra("login", true);
			// startActivity(intent3);
			if (!MatchMeTabWidget.mFacebook.isSessionValid()) {
				MatchMeTabWidget.mFacebook.authorize(this.getParent(),
						PERMISSIONS, new LoginDialogListener());
			} else {
				Log.d("ConnectToActivity", "ERROR ALREADY LOG IN");
			}
			break;

		case (R.id.ConnecttoFacebookDisconnectButton):
			if (MatchMeTabWidget.mFacebook.isSessionValid()) {
				AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(
						MatchMeTabWidget.mFacebook);
				asyncRunner.logout(this.getBaseContext(),
						new LogoutRequestListener());
			} else {
				Log.d("ConnectToActivity",
						"SHOULDN'T LOG OUT IF HAVEN'T LOGGED IN");
			}
			break;

		case (R.id.ConnecttoTwitterConnectButton):
			// TODO Connect to TW
			break;

		case (R.id.ConnecttoTwitterDisconnectButton):
			// TODO DisConnect to TW
			break;
		}
	}
}
